package com.renwei.yunlong.activity.contacts;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.CommonSearchActivity;
import com.renwei.yunlong.activity.news.TranspaintActivity;
import com.renwei.yunlong.activity.me.DisplayEnterpriseInfoActivity;
import com.renwei.yunlong.adapter.SortContactAdapter;
import com.renwei.yunlong.adapter.StartChatListAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.contacts.CompanyContactBean;
import com.renwei.yunlong.bean.contacts.Contact;
import com.renwei.yunlong.event.ChatListCloseEvent;
import com.renwei.yunlong.event.ContactCheckEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.ContactPinyinComparator;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.PinyinUtils;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.utils.UtilList;
import com.renwei.yunlong.view.SearchImage;
import com.renwei.yunlong.view.SimpleOptionView;
import com.renwei.yunlong.utils.CommonUtils;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Project :  yunaandroid.
 * Package name: com.renwei.yunlong.activity.contacts
 * Created by :  Benjamin.
 * Created time: 2017/12/4 18:40
 * Changed by :  Benjamin.
 * Changed time: 2017/12/4 18:40
 * Class description:
 */

public class CompanyContactActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener {
    private static int from_type = 0;
    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.search_image)
    SearchImage mImageSearch;
    @Bind(R.id.rlv_contact)
    ListView mContactListRV;
    @Bind(R.id.btn_commit)
    Button btnCommit;
    @Bind(R.id.rlv_bottom_contact)
    RecyclerView rlvBottomContact;
    @Bind(R.id.pannel_bottom)
    RelativeLayout pannelBottom;
    private String companyCode;
    private String companyName;
    private int pager = 1;
    private String thisCompanyType = "";
    //根据拼音来排列ListView里面的数据类
    private ContactPinyinComparator contactPinyinComparator;
    private SortContactAdapter sortContactAdapter;
    private List<Contact> companyContactItemList;
    private StartChatListAdapter bottomListAdapter;


    public static void OpenActivity(Context context, String companyCode, String thisCompanyTyoe, String companyName, int from_type) {
        Intent intent = new Intent(context, CompanyContactActivity.class);
        intent.putExtra("companyCode", companyCode);
        intent.putExtra("companyName", companyName);
        intent.putExtra("from_type", from_type);
        intent.putExtra("thisCompanyTyoe", thisCompanyTyoe);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_company_contact);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        EventBus.getDefault().register(this);
        from_type = getIntent().getIntExtra("from_type", 0);
        thisCompanyType = StringUtils.value(getIntent().getStringExtra("thisCompanyTyoe"));
        companyCode = StringUtils.value(getIntent().getStringExtra("companyCode"));
        companyName = StringUtils.value(getIntent().getStringExtra("companyName"));
        if (from_type == 0) {
            pannelBottom.setVisibility(View.GONE);
        } else {
            pannelBottom.setVisibility(View.VISIBLE);
        }
        initView();
    }

    private void initView() {
        mImageSearch = (SearchImage) findViewById(R.id.search_image);
        mImageSearch.setOnClickListener(this);
        mContactListRV = (ListView) findViewById(R.id.rlv_contact);
        contactPinyinComparator = new ContactPinyinComparator();
        rlvBottomContact.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
        bottomListAdapter = new StartChatListAdapter(this, thisCompanyType);
        rlvBottomContact.setAdapter(bottomListAdapter);
        btnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TranspaintActivity.openActivity(CompanyContactActivity.this);
                //EventBus.getDefault().post(new CommitMemberEvent(CommitMemberEvent.COMMIT_MEMBER_EVENT));
            }
        });
        simpleTileView.setTitle(companyName);
        simpleTileView.setRightOption(R.mipmap.icon_company, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DisplayEnterpriseInfoActivity.OpenActivity(mContext, companyCode);
            }
        });
        initData();
    }

    private void initData() {
        if ("".equals(companyCode)) {
            return;
        }
        ServiceRequestManager manager = ServiceRequestManager.getManager();
        HashMap<String, String> map = new HashMap<>();
        map.put("companyCode", companyCode);
        map.put("page", StringUtils.value(pager));
        map.put("rows", "20");
        map.put("name", "");
        manager.queryFriendCompanyContact(this, JsonMapUtil.mapToJson(map), this);
        initBottomContactList();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_image:
                CommonSearchActivity.OpenActivityFromFriendCompanyContact(this, v, CommonSearchActivity.class, 997, companyCode, from_type, thisCompanyType);
                break;
            default:
                break;
        }
    }

    //转拼音
    private List<Contact> filledCompanyContactPingYing(List<Contact> companyContactItemList) {
        for (int i = 0; i < companyContactItemList.size(); i++) {
            Contact contact = companyContactItemList.get(i);
            if (contact != null) {
                String name = StringUtils.value(contact.getEmployeeName());
                //汉字转换成拼音
                String pinyin = PinyinUtils.getPingYin(name);
                String sortString = pinyin.substring(0, 1).toUpperCase();
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    contact.setLetter(sortString.toUpperCase());
                } else {
                    contact.setLetter("#");
                }
            }

        }
        return companyContactItemList;
    }

    @Override
    public void onSuccess(int requestId, String result) {
        LogUtil.e("根据企业id查看相关用户信息：" + result);
        CompanyContactBean bean = new Gson().fromJson(result, CompanyContactBean.class);
        if (bean != null) {
            companyContactItemList = bean.getRows();
            if (UtilList.getCount(companyContactItemList) > 0) {
                companyContactItemList = filledCompanyContactPingYing(companyContactItemList);
                Collections.sort(companyContactItemList, contactPinyinComparator);
                sortContactAdapter = new SortContactAdapter(this, from_type, thisCompanyType, companyContactItemList, true);
                mContactListRV.setAdapter(sortContactAdapter);
            }

        }
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getResources().getString(R.string.net_work_error));
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefreshName(ContactCheckEvent event) {
        initBottomContactList();
        if (sortContactAdapter != null) {
            sortContactAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onClosePage(ChatListCloseEvent event) {
        finish();
    }


    public void initBottomContactList() {
        bottomListAdapter.setData(AppHelper.getCheckContactList());
        String commitText = "";
        if (UtilList.getCount(AppHelper.getCheckContactList()) == 0) {
            commitText = "确定";
        } else {
            commitText = "确定(" + UtilList.getCount(AppHelper.getCheckContactList()) + ")";
        }
        btnCommit.setText(commitText);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        EventBus.getDefault().unregister(this);
    }


}
